package com.xmh.ssm.utils.automaticGeneration;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.junit.Test;

public class Word {

	@Test
	public void word2() {
		String readWord = readWord("E:\\文档\\阳西县医院集团卫生信息平台数据接口规范.docx");
		String open = "PlatDiTreat1002";
		String close = "表名";

		String ssb = StringUtils.substringBetween(readWord, open, close);

		
		StringBuffer asSqlSb = new StringBuffer();

		StringBuffer insertSb = new StringBuffer();

		StringBuffer commentSb = new StringBuffer();

		StringBuffer createTableSb = new StringBuffer();

		StringBuffer selectSb = new StringBuffer();

		insertSb.append(
				"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\"\n\"http://ibatis.apache.org/dtd/sql-map-2.dtd\" >\n\n<sqlMap namespace=\"t"
						+ open
						+ "\">\n\t<insert id=\"insertRow\" parameterClass=\"java.util.HashMap\" >\n\t\t<![CDATA[\n\t\t\tINSERT INTO "
						+ open + " (\n");

		createTableSb.append("CREATE TABLE " + open + " ( \n ");

		selectSb.append("select ");

		int i = 0;
		int k = 1;
		String[] split = ssb.substring(ssb.indexOf("为空") + 2).split("\n");
		for (String string : split) {
			i++;
			if (StringUtils.isEmpty(string)) {
				k++;
				continue;
			}

			String[] split2 = string.split("\t");

			if (split2.length < 2) {
				k++;
				continue;
			}

			String name = split2[1].replace(" ", "").toUpperCase();
			String type = split2[4].trim();
			String comment = split2[2].trim();
			String commentPs = split2[3].trim();
			String length = split2[5].replace(" ", "").replace("\n", "");

			commentSb.append("COMMENT ON COLUMN " + open + "." + name + " IS '" + comment);
			if (comment.equals(commentPs)) {
				commentSb.append("';\n");
				asSqlSb.append(" as " + name + ",\t\t/* " + comment + " */\n");
			} else {
				commentSb.append(" - " + commentPs + "';\n");
				asSqlSb.append(" as " + name + ",\t\t/* " + comment + "\t// " + commentPs + " */\n");
			}

			if (length.contains(".")) {
				length = length.replace(" ", "").replace(".", ",");
				createTableSb.append("\"" + name + "\" decimal(" + length + ")");
				selectSb.append("MYDECIMAL as " + name);
			} else if ("N".equals(type)) {
				if (length.contains("decimal")) {
					createTableSb.append("\"" + name + "\"  " + length);
					selectSb.append("MYDECIMAL as " + name);
				} else {
					createTableSb.append("\"" + name + "\" number(" + length + ")");
					selectSb.append("ID as " + name);
				}
			} else if (type.contains("D") || length.contains("yyyy")) {
				createTableSb.append("\"" + name + "\" DATE ");
				selectSb.append("STRAT_DT as " + name);
			} else if (type.contains("BLOB")) {
				createTableSb.append("\"" + name + "\" " + type);
				selectSb.append("MYBLOB as " + name);
			} else if (type.contains("decimal")) {
				createTableSb.append("\"" + name + "\" " + type + "(" + length.replaceAll(",", ".") + ")");
				selectSb.append("MYDECIMAL as " + name);
			} else {
				createTableSb.append("\"" + name + "\" " + type + "(300)");
				selectSb.append("NAME as " + name);
			}

			insertSb.append("\t\t\t\t" + name);

			if (i <= split.length - k) {
				insertSb.append(",");
				createTableSb.append(", \n");
				selectSb.append(", ");
			} else {
				System.out.println();
			}
			insertSb.append("\n");
		}

		selectSb.append(" FROM TEST_DATA ");

		createTableSb.append(");");

		insertSb.append("\t\t\t)  VALUES ( \n");

		i = 0;
		for (String string : split) {
			i++;
			if (StringUtils.isEmpty(string)) {
				continue;
			}
			String[] split2 = string.split("\t");
			if (split2.length < 2) {
				continue;
			}
			String name = split2[1].replace(" ", "").toUpperCase();

			insertSb.append("\t\t\t\t#" + name + "#");

			if (i <= split.length - k) {
				insertSb.append(",");
			}
			insertSb.append("\n");
		}
		insertSb.append("\t\t\t)\n\t\t]]>\n\t</insert>\n</sqlMap>");

		System.out.println(asSqlSb.toString());

		System.out.println("\n\n" + insertSb.toString());

		System.out.println("\n\n" + createTableSb.toString());

		System.out.println("\n\n" + commentSb.toString());

		System.out.println("\n\n" + selectSb.toString());
	}

	@Test
	public void thisMain() {
//		String readWord = readWord("E:\\文档\\阳江\\阳江跨省异地接口就医地升级整改规范1.doc");
		String readWord = readWord("E:\\文档\\阳西县医院集团卫生信息平台数据接口规范.docx");
//		String readWord = readWord("E:\\文档\\阳江\\附件3：阳江市医疗保险异地就医直接结算接口规范.doc");
		String open = "门诊挂号登记信息";
		String close = "门急诊病历信息";

		getSc(readWord, open, close);

		getJsSetValue(readWord, open, close);
	}

	public void getJsSetValue(String readWord, String open, String close) {
		System.out.println("\n\njsdic定义   --  ");
		String[] substringBetween = StringUtils.substringsBetween(readWord, open, close);

		String source = null;

		if (substringBetween.length == 1) {
			source = substringBetween[0];
		} else {
			source = substringBetween[1];
		}

		String ssb = source.replace("参数代码	参数名称	数据类型	可否为空	说明", "").trim();

		ssb = ssb.substring(ssb.indexOf("交易返回xml数据项说明：") + 13).replace("\r", "");

		String[] split = ssb.split("\n");

		String mssg = "以下按明细分列，包含在detail";
		if (ssb.contains(mssg)) {
			for (int i = 0; i < split.length; i++) {
				String str = split[i];

				split[i] = null;

				if (str.contains(mssg)) {
					break;
				}
			}
		}
		StringBuffer sbBuffer = new StringBuffer();

		for (String string : split) {
			if (StringUtils.isEmpty(string)) {
				continue;
			}
			String[] split2 = string.split("\t");

			if (split2.length < 2) {
				continue;
			}

			if (split2[0].equals("aac043")) {
				sbBuffer.append("rowItem.set(\"" + split2[0] + "_text\", ");
				sbBuffer.append("phis.application.yb.script.MedicareUtils.getDicBySfzlb(datas[i].aac043)");
			} else if (split2[0].equals("aac004")) {
				sbBuffer.append("rowItem.set(\"" + split2[0] + "_text\", ");
				sbBuffer.append("phis.application.yb.script.MedicareUtils.getDicBysex(datas[i].aac004)");
			} else if (split2[0].equals("aka130")) {
				sbBuffer.append("rowItem.set(\"" + split2[0] + "_text\", ");
				sbBuffer.append("phis.application.yb.script.MedicareUtils.getDicByYllb(datas[i].aka130)");
			} else if (split2[0].equals("ykc675")) {
				sbBuffer.append("rowItem.set(\"" + split2[0] + "_text\", ");
				sbBuffer.append("phis.application.yb.script.MedicareUtils.getDicByJslb(datas[i].ykc675)");
			} else if (split2[0].equals("yka111")) {
				sbBuffer.append("rowItem.set(\"" + split2[0] + "_text\", ");
				sbBuffer.append("phis.application.yb.script.MedicareUtils.getDicByDldm(datas[i].yka111)");
			} else {
				sbBuffer.append("rowItem.set(\"" + split2[0] + "\", ");
				sbBuffer.append("datas[i]." + split2[0]);
			}
			if (split2.length > 4) {
				sbBuffer.append(" ); // " + split2[1] + "  PS ： " + split2[4] + "\n");
			} else {
				sbBuffer.append(" ); // " + split2[1] + "\n");
			}
		}

		System.out.println(sbBuffer.toString());
	}

	public void getSc(String readWord, String open, String close) {
		String[] substringBetween = StringUtils.substringsBetween(readWord, open, close);

		String source = null;

		if (substringBetween.length == 1) {
			source = substringBetween[0];
		} else {
			source = substringBetween[1];
		}
		String ssb = source.replace("参数代码	参数名称	数据类型	可否为空	说明", "").trim();

		ssb = ssb.substring(ssb.indexOf("交易返回xml数据项说明：") + 13).replace("\r", "");

		String[] split = ssb.split("\n");

		String mssg = "以下按明细分列，包含在detail";
		if (ssb.contains(mssg)) {
			for (int i = 0; i < split.length; i++) {
				String str = split[i];

				split[i] = null;

				if (str.contains(mssg)) {
					break;
				}
			}
		}

		List<String> codeList = new ArrayList<>();

		StringBuffer sbBuffer = new StringBuffer();

		StringBuffer testDataSb = new StringBuffer();
		testDataSb.append("\t\t\treply.detail.row[i] = {};\n");

		for (String string : split) {
			if (StringUtils.isEmpty(string)) {
				continue;
			}
			String[] split2 = string.split("\t");

			String type = null;
			String Length = null;

			if (split2.length < 2) {
				continue;
			}

			testDataSb.append("\t\t\treply.detail.row[i]." + split2[0] + " = 1;\t// " + split2[1] + "\n");

			String dataType = split2[2];

			if (dataType.contains("varchar2")) {
				Length = StringUtils.substringBetween(dataType, "(", ")");
				type = "string\" length=\"" + Length;
			} else if (dataType.contains("date")) {
				type = "date";
			} else if (dataType.contains("number")) {
				Length = StringUtils.substringBetween(dataType, "(", ")");
				if (Length.contains(",")) {
					String[] split3 = Length.split(",");
					type = "double\" length=\"" + split3[0] + "\" precision=\"" + split3[1];
				} else {
					type = "int\" length=\"" + Length;
				}
			}
			sbBuffer.append("\t<item id=\"" + split2[0] + "\" alias=\"" + split2[1] + "\" type=\"" + type + "\" ");

			if (split2.length < 5 || !split2[4].contains("参见代码定义")) {
				sbBuffer.append("/>\n");
				continue;
			}
			String code = split2[4].replaceAll("[\u4e00-\u9fa5]", "");

			codeList.add(code);

			String dic = getDic(code, readWord);

			sbBuffer.append(" >\n");

			sbBuffer.append(dic + "\n");
		}
		System.out.println(sbBuffer.toString());

		System.out.println("test data  --    - -  ");
		System.out.println(testDataSb.toString());
		System.out.println("test data  --    - -  ");

		for (String code : codeList) {
			getJsDic(code, readWord);
		}
	}

	private static String getDic(String code, String readWord) {
		String substr = readWord.substring(readWord.lastIndexOf("单位类型AAB019"));

		substr = substr.substring(substr.indexOf(code));

		String replacement = "gggg";

		substr = substr.replaceAll("[\u4e00-\u9fa5]+[a-zA-Z]", replacement);

		substr = StringUtils.substringBetween(substr, code, replacement);

		substr = substr.replace(code, "").replace("代码	名称", "");

		String replace2 = substr.replace("\r", "").replace("\t", "").replace("\n", "");

		String[] split = replace2.split("[\\d+]");

		String[] sz = new String[split.length * 2];

		int i = 1;

		for (String string : split) {
			if (StringUtils.isNotEmpty(string)) {
				sz[i] = string;
				i += 2;
			}
		}

		i = 0;

		String[] split2 = replace2.split("[^\\d+]");

		for (String string : split2) {
			if (StringUtils.isNotEmpty(string)) {
				sz[i] = string;
				i += 2;
			}
		}

		StringBuffer sbBuffer = new StringBuffer();

		sbBuffer.append("\t\t<dic>\n");
		for (int j = 0; j < sz.length; j++) {
			String str = sz[j];
			if (StringUtils.isNotEmpty(str)) {
				if (j % 2 == 0) {
					sbBuffer.append("\t\t\t<item key=\"" + str + "\" ");
				} else {
					sbBuffer.append("text=\"" + str + "\"/>\n");
				}
			}
		}
		sbBuffer.append("\t\t</dic>\n\t</item>");
		return sbBuffer.toString();
	}

	public void getJsDic(String code, String readWord) {
		System.out.println("\n\n代码定义  code " + code + "\n");

		String substr = readWord.substring(readWord.lastIndexOf("单位类型AAB019"));

		substr = substr.substring(substr.indexOf(code));

		String replacement = "gggg";

		substr = substr.replaceAll("[\u4e00-\u9fa5]+[a-zA-Z]", replacement);

		substr = StringUtils.substringBetween(substr, code, replacement);

		substr = substr.replace(code, "").replace("代码	名称", "");

		String replace2 = substr.replace("\r", "").replace("\t", "").replace("\n", "");

		String[] split = replace2.split("[\\d+]");

		String[] sz = new String[split.length * 2];

		int i = 1;

		for (String string : split) {
			if (StringUtils.isNotEmpty(string)) {
				sz[i] = string;
				i += 2;
			}
		}

		i = 0;

		String[] split2 = replace2.split("[^\\d+]");

		for (String string : split2) {
			if (StringUtils.isNotEmpty(string)) {
				sz[i] = string;
				i += 2;
			}
		}

		StringBuffer sbBuffer = new StringBuffer();

		sbBuffer.append("");
		for (int j = 0; j < sz.length; j++) {
			String str = sz[j];
			if (StringUtils.isNotEmpty(str)) {
				if (j % 2 == 0) {
					sbBuffer.append("if ( dicCode == " + str + " || dicCode == \"" + str + "\") {\n");
				} else {
					sbBuffer.append("\treturn \"" + str + "\";\n} else ");
				}
			}
		}
		System.out.println(sbBuffer.toString());
	}

	/**
	 * 
	 * 
	 * @param path
	 * @return buffer
	 */

	public static String readWord(String path) {
		String buffer = "";
		try {
			if (path.endsWith(".doc")) {
				InputStream is = new FileInputStream(new File(path));
				WordExtractor ex = new WordExtractor(is);
				buffer = ex.getText();

//				ex.close();
			} else if (path.endsWith("docx")) {
				OPCPackage opcPackage = POIXMLDocument.openPackage(path);
				POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
				buffer = extractor.getText();
//				extractor.close();
			} else {
				System.out.println("此文件不是word文件！");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return buffer;
	}

	/**
	 * 读取某个文件夹下的所有文件
	 */
	public static boolean readfile(String filepath) throws FileNotFoundException, IOException {
		try {

			File file = new File(filepath);
			if (!file.isDirectory()) {
				System.out.println("文件");
				System.out.println("path=" + file.getPath());
				System.out.println("absolutepath=" + file.getAbsolutePath());
				System.out.println("name=" + file.getName());

			} else if (file.isDirectory()) {
				System.out.println("文件夹");
				String[] filelist = file.list();
				for (int i = 0; i < filelist.length; i++) {
					File readfile = new File(filepath + "\\" + filelist[i]);
					if (!readfile.isDirectory()) {
						System.out.println("path=" + readfile.getPath());
						System.out.println("absolutepath=" + readfile.getAbsolutePath());
						System.out.println("name=" + readfile.getName());

					} else if (readfile.isDirectory()) {
						readfile(filepath + "\\" + filelist[i]);
					}
				}

			}

		} catch (FileNotFoundException e) {
			System.out.println("readfile()   Exception:" + e.getMessage());
		}
		return true;
	}

	public static void traverseFolder2(String path) {

		File file = new File(path);
		if (file.exists()) {
			File[] files = file.listFiles();
			if (null == files || files.length == 0) {
				System.out.println("文件夹是空的!");
				return;
			} else {
				for (File file2 : files) {
					if (file2.isDirectory()) {
						System.out.println("文件夹:" + file2.getAbsolutePath());
						traverseFolder2(file2.getAbsolutePath());
					} else {
						System.out.println("文件:" + file2.getAbsolutePath());
					}
				}
			}
		} else {
			System.out.println("文件不存在!");
		}
	}

	private static List<File> filelist = new ArrayList<>();

	public static List<File> getFileList(String strPath) {
		File dir = new File(strPath);
		File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				String fileName = files[i].getName();
				if (files[i].isDirectory()) { // 判断是文件还是文件夹
					getFileList(files[i].getAbsolutePath()); // 获取文件绝对路径
				} else if (fileName.endsWith("avi")) { // 判断文件名是否以.avi结尾
					String strFileName = files[i].getAbsolutePath();
					System.out.println("---" + strFileName);
					filelist.add(files[i]);
				} else {
					continue;
				}
			}

		}
		return filelist;
	}

}
